//
//  NetworkService.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/14.
//

import UIKit
import Alamofire

/// 网络服务封装
class NetworkService {
    static let shared = NetworkService()
    
    private let session: Session
    private let interceptor = DomainSwitchInterceptor()
    
    private init() {
        // 配置网络会话
        let configuration = URLSessionConfiguration.af.default
        configuration.timeoutIntervalForRequest = 8 // 8秒超时
        configuration.timeoutIntervalForResource = 20 // 20秒资源超时
        
        session = Session(
            configuration: configuration,
            interceptor: interceptor
        )
    }
    
    func request<T: Decodable>(_ path: String,
                               method: HTTPMethod = .get,
                               parameters: Parameters? = nil,
                               completion: @escaping (Result<T, AFError>) -> Void) {
        session.request("https://\(DomainManager.shared.currentDomain)\(path)",
                        method: method,
                        parameters: parameters)
        .validate()
        .responseDecodable(of: T.self) { [weak self] response in
            switch response.result {
                case .success(let value):
                    // 获取最终使用的域名
                    if let request = response.request,
                       let host = request.url?.host {
                        // 设置该域名为有效域名
                    }
                    
                    completion(.success(value))
                case .failure(let error):
                    
                    completion(.failure(error))
            }
        }
    }
    
}
